package com.computer.demo.mvc.action;

import com.computer.demo.service.IModifyService;
import com.computer.demo.service.IQueryService;
import com.computer.spring.framework.annotation.BYAutowired;
import com.computer.spring.framework.annotation.BYController;
import com.computer.spring.framework.annotation.BYRequestMapping;
import com.computer.spring.framework.annotation.BYRequestParam;
import com.computer.spring.framework.webmvc.BYModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description
 * @Author MagicIce
 * @Date 2020/11/23 9:11
 */
@BYController
@BYRequestMapping("/web")
public class MyAction {

    @BYAutowired
    private IQueryService queryService;

    @BYAutowired
    private IModifyService modifyService;

    @BYRequestMapping("/query.json")
    public BYModelAndView query(HttpServletRequest request, HttpServletResponse response, @BYRequestParam("name") String name){
        return out(response, queryService.query(name));
    }

    @BYRequestMapping("/add*.json")
    public BYModelAndView add(HttpServletRequest request, HttpServletResponse response,
                              @BYRequestParam("name") String name, @BYRequestParam("addr") String addr){
        return out(response, modifyService.add(name, addr));
    }

    @BYRequestMapping("/remove.json")
    public BYModelAndView remove(HttpServletRequest request, HttpServletResponse response, @BYRequestParam("id") Integer id){
        return out(response, modifyService.remove(id));
    }

    @BYRequestMapping("/edit.json")
    public BYModelAndView edit(HttpServletRequest request, HttpServletResponse response,
                               @BYRequestParam("id") Integer id, @BYRequestParam("name") String name){
        return out(response, modifyService.edit(id, name));
    }

    private BYModelAndView out(HttpServletResponse response, String str) {
        try {
            response.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
